<template>
    <div>
        <el-dialog :title="props.isAdd ? '添加商品分类' : '编辑商品分类'" v-model="props.isShow" center :before-close="beforeClose">
            <el-form :model="cateForm" :rules="rules" ref="cateRef">
                <el-form-item label="上级菜单" :label-width="formLabelWidth" prop="pid">
                    <el-select v-model="cateForm.pid" class="m-2" placeholder="Select">
                        <el-option label="顶级分类" :value="0"></el-option>
                        <el-option v-for="item in store.getters['cate/getCate']" :key="item.id" :label="item.catename"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称" :label-width="formLabelWidth" prop="catename">
                    <el-input v-model="cateForm.catename" autocomplete="off" />
                </el-form-item>
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload v-model:file-list="fileList" action="#" list-type="picture-card" :on-preview="onPreview"
                        :on-remove="handleRemove" :on-change="onChange" :limit="1">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="cateForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(cateRef)">取消</el-button>
                    <el-button type="primary" @click="sure(cateRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { defineProps, defineEmits, ref, reactive, defineExpose } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { cateAdd, cateEdit, cateInfo } from '../../request/api'
import { useStore } from 'vuex'
let store = useStore()

//id的值先为0
var newId = 0

//父传子 接收数据
let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})

//子传父
let emit = defineEmits(['cancel'])

//表单对象
let cateForm = ref({
    pid: 0,//上级分类编号
    catename: '',//商品分类名称
    img: '',//图片(文件，一般用于二级分类)
    status: 1,//状态  1正常2禁用
})

//封装一个确定事件
let cateRef = ref<FormInstance>()

//关闭x事件
const beforeClose = (done: any) => {
    done()
    cancel(cateRef.value)
}
//封装一个取消事件
const cancel = (formEl?: FormInstance | undefined) => {
    emit('cancel', false)
    if (!formEl) return
    cateForm.value = {
        pid: 0,//上级分类编号
        catename: '',//商品分类名称
        img: '',//图片(文件，一般用于二级分类)
        status: 1,//状态  1正常2禁用
    }
    //清除表单验证
    formEl.resetFields()
    fileList = []
}


// const fileList = ref<UploadUserFile[]>([])
let fileList: { url: string }[] = []
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
const onChange: UploadProps['onChange'] = (uploadFile) => {
    cateForm.value.img = uploadFile.raw
}

const onPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const formLabelWidth = '120px'

//规则验证
const rules = reactive<FormRules>({
    catename: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, max: 8, message: '长度为2-8个字符', trigger: 'blur' },
    ],
    pid: [
        {
            required: true,
            message: '请选择上级菜单',
            trigger: 'change',
        }
    ]
})


const sure = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((val) => {
        if (val) {
            if (props.isAdd) {
                cateAdd(cateForm.value).then(res => {
                    if (res.code == 200) {
                        console.log(res);
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('cate/getCateListActions')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            } else {
                cateEdit({ ...cateForm.value, id: newId }).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('cate/getCateListActions')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
    })
}

//封装一个数据回显
const lookup = (id: number) => {
    cateInfo({ id }).then((res: any) => {
        // console.log(id);    
        cateForm.value = res.list
        // menuForm.value.id = id
        // console.log(res);
        newId = id
        //图片回显
        fileList = cateForm.value.img ? [{ url: cateForm.value.img }] : []
    })
}

defineExpose({
    lookup
})

</script>
<style lang='less' scoped></style>
